<template>
  <div class="salon_page">
    <div class="salon_search">
      <el-button type="primary" icon="el-icon-edit" size="small" @click="handleCreate">添加实体</el-button>
      <el-input v-model="cdtSname" placeholder="店铺" size="small" clearable style="width: 180px"></el-input>
      <el-input v-model="cdtAddress" placeholder="地址" size="small" clearable style="width: 180px"></el-input>
      <el-input v-model="cdtMname" placeholder="中台社群" size="small" clearable style="width: 180px"></el-input>
      <el-input v-model="cdtDeveloper" placeholder="开发人员" size="small" clearable style="width: 180px"></el-input>
      <el-select v-model="cdnStatus" placeholder="机构状态" size="small" clearable style="width: 180px">
        <el-option :key="0" label="履约期" :value="0"></el-option>
        <el-option :key="1" label="试用期" :value="1"></el-option>
        <el-option :key="2" label="停滞期" :value="2"></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" size="small" @click="searchSalon">查询</el-button>
      <el-button icon="el-icon-refresh" size="small" @click="resetSalon">重置</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column fixed prop="code" label="店家编号" align="left" width="130"></el-table-column>
      <el-table-column
        fixed
        prop="sname"
        label="店铺全称"
        align="left"
        width="200"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="address" label="店家地址" align="left" width="300" show-overflow-tooltip></el-table-column>
      <el-table-column prop="area" label="店铺面积㎡" align="center" width="100"></el-table-column>
      <el-table-column prop="cnumber" label="店铺人数" align="center" width="80"></el-table-column>
      <el-table-column
        prop="developer"
        label="开发人员"
        align="center"
        width="80"
        show-overflow-tooltip></el-table-column>
      <el-table-column label="履约开始" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.bgntime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="履约结束" width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.endtime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构状态" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.status | parseStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="server" label="专属客服" align="center" width="80" show-overflow-tooltip></el-table-column>
      <el-table-column prop="history" label="历史客服" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="150">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" plain @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" plain @click="handleDelete(row.id, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"></pagination>

    <!--添加或修改门店-->
    <el-dialog :title="isAdd ? '添加' : '修改'" :visible.sync="salonFormVisible" style="margin-top: -120px">
      <el-form ref="dataForm" :model="salonObj" label-width="110px" size="small" :rules="rules">
        <el-row :gutter="0">
          <el-col :span="12" :offset="0">
            <el-form-item label="店铺全称" prop="sname">
              <el-input
                v-model="salonObj.sname"
                maxlength="33"
                show-word-limit
                clearable
                style="width: 280px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            大B端:
            <el-select v-model="salonObj.bid" placeholder="请选择大B端" size="small" style="width: 200px">
              <el-option v-for="item in listB" :key="item.id" :label="item.bname" :value="item.id"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-form-item v-show="!isAdd" label="店家编号">
          <el-input v-model="salonObj.code" :disabled="true" style="width: 280px"></el-input>
        </el-form-item>
        <el-form-item label="店家地址">
          <div style="display: grid">
            <region-select ref="refRegionSelect" :mode="1" :dept="2" @change="handleRegionChange"></region-select>
            <el-input
              v-model="salonObj.address"
              autocomplete="off"
              maxlength="66"
              show-word-limit
              style="width: 530px"
              placeholder="街道门牌号"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="店铺业态(多选)">
          <el-select v-model="checkList" multiple placeholder="请选择店铺业态" size="small" style="width: 530px">
            <el-option label="【生美】美睫美甲纹绣" value="1"></el-option>
            <el-option label="【生美】面（头）部类" value="2"></el-option>
            <el-option label="【生美】身体类" value="3"></el-option>
            <el-option label="【生美】中医养生类" value="4"></el-option>
            <el-option label="【生美】大健康类" value="5"></el-option>
            <el-option label="【轻医美机构】" value="6"></el-option>
            <el-option label="【综合医美机构】" value="7"></el-option>
            <el-option label="【异业】服务女性的非美业" value="8"></el-option>
            <el-option label="其他" value="9"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="中台社群">
          <el-radio-group v-model="salonObj.mid">
            <el-radio v-for="(item, index) in lstComms" :key="index" :label="item.id" style="margin-right: 10px">
              {{ item.nickName }}
            </el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="所属集团">
          <el-radio-group v-model="salonObj.oid">
            <el-radio-button
              v-for="(item, index) in lstYm"
              :key="index"
              :label="item.id"
              @click.native="salonObj.oname = item.nickName">
              {{ item.nickName }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="0">
          <el-col :span="7" :offset="0">
            <el-form-item label="联系方式">
              <el-input v-model="salonObj.tel"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item label="店铺面积(㎡)">
              <el-input-number
                v-model="salonObj.area"
                :min="1"
                controls-position="right"
                style="width: 100px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item label="店铺人数">
              <el-input-number
                v-model="salonObj.cnumber"
                :min="1"
                controls-position="right"
                style="width: 100px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="7" :offset="0">
            <el-form-item label="开发人员">
              <el-input v-model="salonObj.developer"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item label="专属客服">
              <el-input v-model="salonObj.server"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-bottom: 10px" label-width="100px" label="机构状态">
          <el-radio v-model="salonObj.status" :label="0">履约期</el-radio>
          <el-radio v-model="salonObj.status" :label="1">试用期</el-radio>
          <el-radio v-model="salonObj.status" :label="2">停滞期</el-radio>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input v-model="salonObj.remark" maxlength="33" show-word-limit style="width: 530px"></el-input>
        </el-form-item>
        <el-form-item label="历史客服">
          <el-input
            v-model="salonObj.history"
            :autosize="{ minRows: 1, maxRows: 4 }"
            type="textarea"
            style="width: 530px"
            disabled></el-input>
        </el-form-item>
        <el-form-item label="合作条款">
          <el-input
            v-model="salonObj.terms"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            maxlength="333"
            show-word-limit
            style="width: 530px"></el-input>
        </el-form-item>
        <el-form-item v-show="isAdd" label="履约周期">
          <el-date-picker
            v-model="beginTime"
            style="width: 200px; margin-right: 15px"
            type="date"
            placeholder="起始日期"></el-date-picker>
          -
          <el-date-picker
            v-model="endTime"
            style="width: 200px; margin-left: 10px"
            type="date"
            placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="问题">
          <el-input
            v-model="salonObj.problem"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            maxlength="333"
            show-word-limit
            style="width: 530px"></el-input>
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input
            v-model="salonObj.solution"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            maxlength="333"
            show-word-limit
            style="width: 530px"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-top: -30px">
        <el-button @click="salonFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入后端 API
import { getAdminsByDuties } from '@/api/admin';
import { addSalon, delSalon, editSalon, getBigbs, getSalonList2, getSomeSalon } from '@/api/txs';
// 引入自定义组件
import Pagination from '@/components/Pagination';
import '@/utils/datefmt';
import RegionSelect from './RegionSelect.vue';
// 引入第三方组件
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';

export default {
  components: { Pagination, ['region-select']: RegionSelect },
  filters: {
    parseTime(time) {
      if (time) {
        return dayjs(time).format('YYYY-MM-DD');
      }
    },
    parseStatus(status) {
      switch (status) {
        case 0:
          return '履约期';
        case 1:
          return '试用期';
        case 2:
          return '停滞期';
      }
    },
  },
  data() {
    return {
      cdtSname: '',
      cdtAddress: '',
      cdtMname: '',
      cdtDeveloper: '',
      cdnStatus: undefined,
      listB: [],
      beginTime: '',
      endTime: '',
      total: 0,
      listQuery: {
        page: 1,
        limit: 12,
      },
      lstComms: [],
      lstBranch: [],
      lstYm: [],
      checkList: [],
      salonFormVisible: false,
      isAdd: false,
      salonObj: {
        id: undefined,
        bid: 0,
        code: '',
        sname: '',
        address: '',
        area: 0,
        pic: '',
        stype: '',
        chat: '',
        developer: '',
        tel: '',
        cnumber: 0,
        bigbend: '',
        track: '',
        createTime: new Date(),
        status: 0,
        server: '',
        history: '',
        mid: undefined,
        oid: undefined,
        jid: undefined,
        oname: '',
        jname: '',
        mname: '',
        regionCode: '',
        regionPath: null,
      },
      list: null,
      listLoading: true,
      rules: {
        sname: [{ required: true, message: '必填项', trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapGetters(['name']),
  },
  created() {
    this.fetchData();
    // getAdminsByDuties(21, 1, 999, 5, 0).then(res => {
    //   this.lstComms = res.data.data.records;
    // });
    getAdminsByDuties(14, 1, 999, 5, 0).then(res => {
      this.lstYm = res.data.data.records;
    });
    getAdminsByDuties(15, 1, 999, 5, 0).then(res => {
      this.lstBranch = res.data.data.records;
    });
  },
  methods: {
    searchSalon() {
      if (
        this.cdnStatus !== undefined ||
        this.cdtAddress !== '' ||
        this.cdtDeveloper !== '' ||
        this.cdtMname !== '' ||
        this.cdtSname !== ''
      ) {
        this.listLoading = true;
        getSomeSalon(this.cdnStatus, this.cdtSname, this.cdtAddress, this.cdtMname, this.cdtDeveloper).then(res => {
          this.list = res.data.data;
          this.total = 0;
          this.listLoading = false;
        });
      }
    },
    resetSalon() {
      this.cdnStatus = undefined;
      this.cdtSname = '';
      this.cdtAddress = '';
      this.cdtMname = '';
      this.cdtDeveloper = '';
      this.listLoading = true;
      getSalonList2(1, 12).then(res => {
        this.list = res.data.data.records;
        this.total = res.data.data.total;
        this.listLoading = false;
      });
    },
    handleRegionChange: async function (rg) {
      if (rg) {
        this.salonObj.address = rg.location + '-';
        this.salonObj.code = rg.salonCode;
        this.salonObj.regionCode = rg.regionCode;
        this.salonObj.regionPath = rg.regionPath;
      }
    },
    fetchData() {
      this.listLoading = true;
      getSalonList2(this.listQuery.page, this.listQuery.limit).then(res => {
        this.list = res.data.data.records;
        this.total = res.data.data.total;
        this.listLoading = false;
      });
      getBigbs().then(res => {
        this.listB = res.data.data;
      });
    },
    handleCreate: async function () {
      this.isAdd = true;
      this.salonObj = this.$options.data().salonObj;
      this.checkList = [];
      this.salonFormVisible = true;
      await this.$nextTick();
      this.$refs['dataForm'].clearValidate();
    },
    handleUpdate: async function (row) {
      this.isAdd = false;
      this.salonFormVisible = true;
      this.salonObj = Object.assign({}, row);
      if (this.salonObj.stype) {
        this.checkList = this.salonObj.stype.split(' ');
      } else {
        this.checkList = [];
      }
      await this.$nextTick();
      this.$refs['dataForm'].clearValidate();
      if (row.regionPath && row.regionPath.length) {
        this.$refs.refRegionSelect.setRegionPath(row.regionPath);
      }
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.salonObj);
          if (tempData.mid && tempData.mid !== 0) {
            // tempData.mname = this.lstComms.find(c => {
            //   return c.id === tempData.mid;
            // }).nickName;
          }
          if (this.isAdd) {
            tempData.createTime = undefined;
            tempData.stype = this.checkList.join(' ');
            let bgTime = '【 2023年07月27日 】 ';
            let edTime = '至 【 2033年07月27日 】';
            if (this.beginTime !== '') {
              bgTime = '【 ' + dayjs(this.beginTime).format('YYYY年MM月DD日') + ' 】 ';
              tempData.bgntime = this.beginTime.format('yyyy-MM-dd HH:mm:ss');
            }
            if (this.endTime !== '') {
              edTime = '至 【 ' + dayjs(this.endTime).format('YYYY年MM月DD日') + ' 】';
              tempData.endtime = this.endTime.format('yyyy-MM-dd HH:mm:ss');
            }
            tempData.period = bgTime + edTime;
            const dlDate = new Date();
            dlDate.setDate(dlDate.getDate() + 30);
            tempData.deadline = dlDate.format('yyyy-MM-dd HH:mm:ss');
            tempData.quota = 10;
            addSalon(tempData).then(res => {
              const d = res.data.data;
              this.list.unshift(d);
              this.salonFormVisible = false;
              this.$message({ type: 'success', message: '添加成功' });
            });
          } else if (!this.isAdd) {
            tempData.stype = this.checkList.join(' ');
            editSalon(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.salonObj.id);
              this.list.splice(index, 1, tempData);
              this.salonFormVisible = false;
              this.$message({ type: 'success', message: '更新成功' });
            });
          }
        }
      });
    },
    handleDelete(id, index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delSalon(id).then(() => {
            this.$message({ type: 'success', message: '删除成功' });
          });
          this.list.splice(index, 1);
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/scrollbar.scss';

.salon_page {
  width: 100%;

  .salon_search {
    padding: 5px 16px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    gap: 5px;
  }
}

::v-deep .el-table td {
  padding: 5px 0;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}

::v-deep .salon_search .el-input {
  width: auto;
}
</style>
